package misc;

public class PattermMatch
{
    private String myPara;
    private String myPattern;
    
    public PattermMatch(String pattern)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("In computer science, pattern matching is the act of ");
        sb.append("checking some sequence of tokens for the presence of the ");
        sb.append("constituents of some pattern. In contrast to pattern");
        sb.append("The patterns generally have the form of either sequences ");
        sb.append("or tree structures.");
        myPara = sb.toString();
        myPattern = pattern;
    }
    
    public int match()
    {
        for (int i = 0; i < myPara.length() - myPattern.length() + 1; i++) {
            boolean found = true;
            for (int j = 0; j < myPattern.length(); j++) {
                if (myPara.charAt(i + j) != myPattern.charAt(j)) {
                    found = false;
                    break;
                }
            }
            if (found) {
                return i;
            }
        }
        return -1;
    }
    
    public int matchPattern()
    {
        int n = myPara.length();
        int m = myPattern.length();
        for(int i=0; i < n; i++) {  // Run at most n times.
            int k = 0;
            while (k < m && (myPattern.charAt(k) == myPara.charAt(i + k))) {
                k ++;   // Run at most m times
            }
            if (k == m) {
                return i;
            }
        }
        
        return -1;
    }
        
    public static void main(String[] args)
    {
        System.out.println("Enter Pattern: ");
        PattermMatch pm = new PattermMatch(args[0]);
        
        int index = pm.match();
        if (index == -1) {
            System.out.println("Pattern did not match :(");
        }
        else {
            System.out.println("Pattern matched at index " + index + " :)");
        }
    }
}
